package com.admin_springboot.adminspringboot.service;

import com.admin_springboot.adminspringboot.entity.Menu;
import com.admin_springboot.adminspringboot.entity.User;
import com.admin_springboot.adminspringboot.mapper.LoginMapper;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class LoginService {

    @Autowired
    private LoginMapper loginMapper;

    public List<User> login(User user) {
        List<User> data = loginMapper.login(user);
        return data;
    }

    public List loadMenu() {
        List<Menu> data = loginMapper.loadMenu();
        List<Map<String, Object>> list = listToTree(data, "parentId");
        return list;
    }
    public static <T> List<Map<String, Object>> listToTree(List<T> entityList, String parentFieldName){
        List<Map<String, Object>> treeMap = new ArrayList<>();
        List<Map<String, Object>> listMap = JSON.parseObject(JSON.toJSONString(entityList), List.class);
        Map<String, Map<String, Object>> entityMap = new Hashtable<>();
        listMap.forEach(map -> entityMap.put(map.get("id").toString(), map));
        listMap.forEach(map -> {
            Object pid = map.get(parentFieldName);
            if (pid == null){
                treeMap.add(map);
            } else {
                Map<String, Object> parentMap = entityMap.get(String.valueOf(pid));
                if (parentMap == null){
                    treeMap.add(map);
                } else {
                    List<Map<String, Object>> children = (List<Map<String, Object>>)parentMap.get("children");
                    if (children == null){
                        children = new ArrayList<>();
                        parentMap.put("children", children);
                    }
                    children.add(map);
                }
            }
        });
        return treeMap;
    }
}
